const API_BASE_URL = import.meta.env.VITE_API_BASE_URL + '/api';

// 获取验证码
export const getCaptcha = async () => {
  const response = await fetch(`${API_BASE_URL}/auth/captcha`);
  if (!response.ok) throw new Error('获取验证码失败');
  return await response.json();
};

// 登录
export const login = async (username, password, captchaId, captchaAnswer) => {
  const response = await fetch(`${API_BASE_URL}/auth/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ username, password, captchaId, captchaAnswer }),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || '登录失败');
  }

  return await response.json();
};

// 登出
export const logout = async (token) => {
  const response = await fetch(`${API_BASE_URL}/auth/logout`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || '登出失败');
  }

  return await response.json();
};

// 修改密码
export const changePassword = async (token, oldPassword, newPassword) => {
  const response = await fetch(`${API_BASE_URL}/auth/password`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify({ oldPassword, newPassword }),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || '修改密码失败');
  }

  return await response.json();
};

